package plugins

import (
	"errors"
	zh_cn "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
)

var instance *Validator

func NewValidator() *Validator {
	return instance
}

func init() {
	instance = &Validator{}
	instance.init()
}

type Validator struct {
	validate *validator.Validate
	trans    ut.Translator
}

// Init 初始化
func (this *Validator) init() {
	zh := zh_cn.New()
	uni := ut.New(zh, zh)
	this.trans, _ = uni.GetTranslator("zh")

	this.validate = validator.New()
	this.validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		label := field.Tag.Get("label")
		if label == "" {
			return field.Name
		}
		return label
	})
	_ = zh_translations.RegisterDefaultTranslations(this.validate, this.trans)
}

// Translate 错误转换
func (this *Validator) Translate(err error) string {
	errs := err.(validator.ValidationErrors)
	var errList []string
	for _, e := range errs {
		// can translate each error one at a time.
		errList = append(errList, e.Translate(this.trans))
	}
	return strings.Join(errList, "|")
}

func (this *Validator) Validate(data interface{}) error {
	err := this.validate.Struct(data)
	if err != nil {
		return errors.New(this.Translate(err))
	}
	return nil
}
